package org.wby.jwt.config.security;

import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.wby.jwt.config.props.SecurityProperties;
import org.wby.jwt.dto.UserDTO;
import org.wby.jwt.enums.SecutityEnums;
import org.wby.jwt.enums.UserEnums;
import org.wby.jwt.service.UserSerivce;
import org.wby.jwt.utils.JWTUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class JwtAuthcationFilter extends OncePerRequestFilter {
    @Autowired
    UserSerivce userSerivce;
    @Autowired
    private JWTUtil jWTUtil;
    @Autowired
    SecurityProperties securityProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从header中获取 jwt
        String jwt = request.getHeader("accessToken");
        //从请求头中取出 jwt，进行判断，如果没有携带 jwt，则继续往下走其他的其他的filter逻辑
        if (!StringUtils.hasText(jwt)) {
            filterChain.doFilter(request,response);
            return;
        }
        //有jwt，验证
        UsernamePasswordAuthenticationToken authentication=getAuthentication(jwt, response);

        // 设置用户登录状态;获取用户信息，存入context
        // 添加了下面这行代码，之后的认证Filter就不会再对当前请求进行认证了
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(String jwt, HttpServletResponse response) {
        JwtParser parser = Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(securityProperties.getSecKey().getBytes(StandardCharsets.UTF_8)))
                .build();
        Claims claims = parser.parseSignedClaims(jwt).getPayload();
        String jwtJson = claims.get(SecutityEnums.USER_CONTEXT.getValue()).toString();

        UserDTO userDTO = new Gson().fromJson(jwtJson, UserDTO.class);
        //用户角色
        List<GrantedAuthority> auths = new ArrayList<>();
        auths.add(new SimpleGrantedAuthority("ROLE_" + UserEnums.MANAGER));
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDTO.getUsername(),null,auths);
        authentication.setDetails(userDTO);

        return authentication;

    }
}
